currentWindowZIndex = 1000;
let isDragging = false;
let dragOffsetX, dragOffsetY;
let currentWindow = null;
let isResizing = false;
let resizeDirection = null;
let initialWidth, initialHeight, initialX, initialY;
let powerMenuOpen = false;
let calendarOpen = false;

function createBlurOverlay() {
  const overlay = document.createElement('div');
  overlay.className = 'blur-overlay';
  overlay.style.zIndex = '9990';
  document.body.appendChild(overlay);
  return overlay;
}

const blurOverlay = createBlurOverlay();

function setWallpaper() {
  const wallpaper = document.querySelector('.wallpaper');
  wallpaper.style.backgroundImage = "url('background.png')";
}

function initDragEvents() {
  document.addEventListener('DOMContentLoaded', function() {
    document.addEventListener('mousedown', startDrag);
    document.addEventListener('touchstart', startDrag, { passive: false });
    
    document.addEventListener('mousemove', drag);
    document.addEventListener('touchmove', drag, { passive: false });
    
    document.addEventListener('mouseup', endDrag);
    document.addEventListener('touchend', endDrag);
    document.addEventListener('touchcancel', endDrag);
  });
}

function startDrag(e) {
  if (e.type === 'mousedown') {
    if (e.target.classList.contains('window-header')) {
      currentWindow = e.target.closest('.window');
    } else {
      return;
    }
  } 
  else if (e.type === 'touchstart') {
    const touch = e.touches[0];
    const targetElement = document.elementFromPoint(touch.clientX, touch.clientY);
    if (targetElement && targetElement.classList.contains('window-header')) {
      currentWindow = targetElement.closest('.window');
    } else {
      return;
    }
    e.preventDefault();
  }
  
  if (!currentWindow) return;
  
  bringWindowToFront(currentWindow);
  
  isDragging = true;
  const rect = currentWindow.getBoundingClientRect();
  
  if (e.type === 'mousedown') {
    dragOffsetX = e.clientX - rect.left;
    dragOffsetY = e.clientY - rect.top;
  } else {
    const touch = e.touches[0];
    dragOffsetX = touch.clientX - rect.left;
    dragOffsetY = touch.clientY - rect.top;
  }
  
  currentWindow.style.zIndex = currentWindowZIndex++;
  currentWindow.classList.add('dragging');
}

function drag(e) {
  if (!isDragging || !currentWindow) return;
  
  e.preventDefault();
  
  let clientX, clientY;
  
  if (e.type === 'mousemove') {
    clientX = e.clientX;
    clientY = e.clientY;
  } else {
    const touch = e.touches[0];
    clientX = touch.clientX;
    clientY = touch.clientY;
  }
  
  const x = clientX - dragOffsetX;
  const y = clientY - dragOffsetY;
  
  currentWindow.style.left = x + 'px';
  currentWindow.style.top = y + 'px';
  
  if (currentWindow.classList.contains('maximized')) {
    currentWindow.classList.remove('maximized');
  }
}

function endDrag() {
  if (isDragging && currentWindow) {
    currentWindow.classList.remove('dragging');
  }
  
  isDragging = false;
  currentWindow = null;
}

function initStartMenu() {
  document.addEventListener('DOMContentLoaded', function() {
    const startButton = document.getElementById('startButton');
    if (startButton) {
      startButton.addEventListener('click', togglePowerMenu);
      startButton.addEventListener('dblclick', togglePowerMenu);
    }

    const datetimeElement = document.querySelector('.datetime');
    if (datetimeElement) {
      datetimeElement.addEventListener('click', toggleCalendarPopup);
      datetimeElement.addEventListener('dblclick', toggleCalendarPopup);
    }
  });
}

function updateDateTime() {
  const datetimeText = document.getElementById('datetimeText');
  const now = new Date();
  
  const options = { 
    hour: '2-digit',
    minute: '2-digit'
  };
  
  datetimeText.textContent = now.toLocaleString('zh-CN', options);
}

function togglePowerMenu() {
  const powerMenu = document.getElementById('powerMenuPopup');
  const isOpen = powerMenu.classList.contains('show');
  
  if (isOpen) {
    powerMenu.classList.remove('show');
    powerMenuOpen = false;
    if (!calendarOpen) {
      blurOverlay.classList.remove('active');
    }
  } else {
    powerMenu.classList.add('show');
    powerMenuOpen = true;
    blurOverlay.classList.add('active');
  }
}

function showCalendarPopup() {
  const calendarPopup = document.getElementById('calendarPopup');
  const calendarContent = document.getElementById('calendarContent');
  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = now.getMonth(); 
  const currentDay = now.getDate();

  // 添加月份导航功能 - 重置到当前日期
  if (!window.calendarState) {
    window.calendarState = {
      year: currentYear,
      month: currentMonth
    };
  }

  // 中国节假日数据（示例）
  const holidays = {
    '2024-1-1': '元旦',
    '2024-2-10': '春节',
    '2024-4-4': '清明节',
    '2024-5-1': '劳动节',
    '2024-6-10': '端午节',
    '2024-9-17': '中秋节',
    '2024-10-1': '国庆节'
  };

  const weekNames = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
  const weekShort = ['日','一','二','三','四','五','六'];
  const weekDay = weekNames[now.getDay()];
  const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];


  
  function getDaysInYear(year) {
    return isLeapYear(year) ? 366 : 365;
  }
  
  function isLeapYear(year) {
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
  }
  
  function getDaysInMonth(year, month) {
    const monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (month === 1 && isLeapYear(year)) {
      return 29;
    }
    return monthDays[month] || 30;
  }
  // 日历头部：年月显示
  let html = `
    <div style="padding: 8px 0 12px 0; display: flex; justify-content: center; align-items: center; border-bottom: 1px solid rgba(0,0,0,0.05);">
      <h3 style="font-size: 18px; font-weight: 500; margin: 0;">${monthNames[window.calendarState.month]} ${window.calendarState.year}</h3>
    </div>
  `;

  // 当前日期信息显示 - 显示精确到秒的当前时间
  function updateCurrentTime() {
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    return hours + ':' + minutes + ':' + seconds;
  }
  const currentTime = updateCurrentTime();
  html += `
    <div style="padding: 12px 0; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(0,0,0,0.05);">
      <div>
        <div style="font-size: 14px; color: #666;">今天</div>
        <div style="font-size: 24px; font-weight: 600;">${currentDay}</div>
        <div style="font-size: 14px; color: #666;">${weekDay}</div>
      </div>
      <div style="text-align: right;">
        <div style="font-size: 14px; color: #666;">当前时间</div>
        <div style="font-size: 24px; font-weight: 600;" id="currentTimeDisplay">${currentTime}</div>
      </div>
      <script>
        // 添加实时刷新时间的功能
        if (window.timeUpdateInterval) {
          clearInterval(window.timeUpdateInterval);
        }
        function updateLiveTime() {
          const now = new Date();
          const hours = String(now.getHours()).padStart(2, '0');
          const minutes = String(now.getMinutes()).padStart(2, '0');
          const seconds = String(now.getSeconds()).padStart(2, '0');
          const timeDisplay = document.getElementById('currentTimeDisplay');
          if (timeDisplay) {
            timeDisplay.textContent = hours + ':' + minutes + ':' + seconds;
          }
        }
        // 立即更新一次
        updateLiveTime();
        // 每秒更新一次
        window.timeUpdateInterval = setInterval(updateLiveTime, 1000);
        
        // 确保在日历关闭时清除定时器
        const calendarElement = document.getElementById('calendarPopup');
        const observer = new MutationObserver((mutations) => {
          mutations.forEach(mutation => {
            if (mutation.attributeName === 'class' && !calendarElement.classList.contains('show')) {
              if (window.timeUpdateInterval) {
                clearInterval(window.timeUpdateInterval);
                window.timeUpdateInterval = null;
              }
              observer.disconnect();
            }
          });
        });
        observer.observe(calendarElement, { attributes: true });
      </script>
    </div>
  `;

  // 日历表格
  html += `<table style="width:100%; max-width:500px; margin:0 auto; border-collapse:collapse;text-align:center;font-size:16px;table-layout:fixed; border-spacing: 0;">
    <thead>
      <tr style="color:#666;">
        ${weekShort.map(w=>`<th style="padding:12px 0; min-width:40px; max-width:40px;">${w}</th>`).join('')}
      </tr>
    </thead>
    <tbody>
      <tr>
  `;

  const firstDay = new Date(window.calendarState.year, window.calendarState.month, 1);
  let firstWeekDay = firstDay.getDay();

  const daysInMonth = getDaysInMonth(window.calendarState.year, window.calendarState.month);

  let col = 0;
  // 填充上月剩余天数并显示实际日期
  const prevMonth = window.calendarState.month - 1;
  const prevYear = window.calendarState.month === 0 ? window.calendarState.year - 1 : window.calendarState.year;
  const daysInPrevMonth = getDaysInMonth(prevYear, prevMonth);
  
  for (let i = 0; i < firstWeekDay; i++) {
    const prevDay = daysInPrevMonth - (firstWeekDay - i - 1);
    html += `<td style="padding:12px 0; color:#ccc; min-width:40px; max-width:40px; height:40px;"><span>${prevDay}</span></td>`;
    col++;
  }
  
  // 填充当月天数
  for (let d = 1; d <= daysInMonth; d++) {
    const dateKey = `${window.calendarState.year}-${window.calendarState.month + 1}-${d}`;
    let style = "padding:12px 0; border-radius:6px; transition:background 0.2s; cursor:pointer; user-select: none; min-width:40px;";
    let className = "";
    
    // 判断是否是今天
    if (d === currentDay && window.calendarState.year === currentYear && window.calendarState.month === currentMonth) {
      style += "background:#0078D4;color:#fff;font-weight:bold;";
      className = "today";
    }
    // 判断是否是节假日
    else if (holidays[dateKey]) {
      style += "color:#d13438;";
    }
    // 判断是否是周末
    const dayOfWeek = new Date(window.calendarState.year, window.calendarState.month, d).getDay();
    if (dayOfWeek === 0 || dayOfWeek === 6) {
      if (d !== currentDay || window.calendarState.year !== currentYear || window.calendarState.month !== currentMonth) {
        style += "color:#0078D4;";
      }
    }
    
    html += `<td style="${style} max-width:40px; height:40px;" class="${className}" onclick="event.stopPropagation(); selectCalendarDate(${d}, ${window.calendarState.month}, ${window.calendarState.year})"><span>${d}</span>${holidays[dateKey] ? `<div style="font-size:10px;">${holidays[dateKey]}</div>` : ''}</td>`;
    col++;
    if (col === 7 && d !== daysInMonth) {
      html += '</tr><tr>';
      col = 0;
    }
  }
  
  // 填充下月剩余天数并显示实际日期，确保总共显示6行
  const nextMonth = window.calendarState.month + 1;
  const nextYear = window.calendarState.month === 11 ? window.calendarState.year + 1 : window.calendarState.year;
  let nextDay = 1;
  
  // 确保总共显示6行
  const totalCells = 6 * 7; // 6行，每行7天
  const filledCells = firstWeekDay + daysInMonth;
  const remainingCells = totalCells - filledCells;
  
  for (let i = 0; i < remainingCells; i++) {
    html += `<td style="padding:12px 0; color:#ccc; min-width:40px; max-width:40px; height:40px;"><span>${nextDay}</span></td>`;
    nextDay++;
    col++;
    if (col === 7 && i < remainingCells - 1) {
      html += '</tr><tr>';
      col = 0;
    }
  }
  
  // 确保日历表格高度固定和单元格显示正确
  html += '</tr></tbody></table><style>#calendarPopup { min-height: 400px; } #calendarContent table td, #calendarContent table th { display: table-cell; vertical-align: middle; white-space: nowrap; }</style>';

  // 移除动画效果，因为不再需要切换月份
  calendarContent.innerHTML = html;
  calendarContent.style.opacity = '1';
  calendarContent.style.transform = 'translateY(0)';

  calendarPopup.classList.add('show');
  blurOverlay.classList.add('active');
  calendarOpen = true;
}



// 选择日历日期的函数
function selectCalendarDate(day, month, year) {
  // 这里可以添加日期选择的逻辑
  console.log('Selected date:', day, month + 1, year);
  // 可以添加日期选择后的回调或其他操作
}

function hideCalendarPopup() {
  const calendarPopup = document.getElementById('calendarPopup');
  calendarPopup.classList.remove('show');
  calendarOpen = false;
  
  // 重置日历状态到当前日期，以便下次打开时显示今天
  const now = new Date();
  window.calendarState = {
    year: now.getFullYear(),
    month: now.getMonth()
  };
  
  if (!document.querySelector('.power-menu-popup.show') && 
      !document.querySelector('.power-confirm-popup.show')) {
    blurOverlay.classList.remove('active');
  }
}

function generateWindowId() {
  return 'app-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
}

function createNewWindow(windowId, appName = '测试应用', homeUrl) {
  const window = document.createElement('div');
  window.className = 'window test-app';
  window.id = windowId;
  window.style.display = 'block';
  window.style.position = 'absolute';
  window.style.width = '800px';
  window.style.height = '600px';
  window.style.left = '50px';
  window.style.top = '50px';
  window.innerHTML = `
    <div class="window-header" onselectstart="return false">
      <div class="window-title">
        ${appName}
        <div class="loading-wrapper">
          <span class="separator">|</span>
          <span class="loading-text">加载中</span>
          <div class="loading-animation"></div>
        </div>
      </div>
      <div class="url-display-container">
        <div class="url-display" id="urlDisplay-${windowId}"></div>
      </div>
      <div class="window-buttons">
        <button class="window-btn back" onclick="goBack('${windowId}')" title="后退">
          <img src="/img/right.svg" alt="后退" style="width:100%;height:100%;object-fit:contain;transform: rotate(180deg);">
        </button>
        <button class="window-btn home" onclick="goHome('${windowId}')">
          <img src="/img/home.svg" alt="主页" style="width:100%;height:100%;object-fit:contain;">
        </button>
        <button class="window-btn refresh" onclick="refreshPage('${windowId}')">
          <img src="/img/refresh.svg" alt="刷新" style="width:100%;height:100%;object-fit:contain;">
        </button>
        <button class="window-btn minimize" onclick="minimizeWindow('${windowId}')">
          <img src="/img/m.svg" alt="最小化" style="width:100%;height:100%;object-fit:contain;">
        </button>
        <button class="window-btn maximize" onclick="maximizeWindow('${windowId}')">
          <img src="/img/b.svg" alt="最大化" style="width:100%;height:100%;object-fit:contain;">
        </button>
        <button class="window-btn close" onclick="closeWindow('${windowId}')">
          <img src="/img/c.svg" alt="关闭" style="width:100%;height:100%;object-fit:contain;">
        </button>
      </div>
    </div>
    <div class="window-content">
      <iframe id="appIframe-${windowId}" name="appIframe-${windowId}"
        style="width:100%; height:100%; border:none;"></iframe>
    </div>
    <div class="resize-handle resize-handle-nw" data-direction="nw"></div>
    <div class="resize-handle resize-handle-n" data-direction="n"></div>
    <div class="resize-handle resize-handle-ne" data-direction="ne"></div>
    <div class="resize-handle resize-handle-w" data-direction="w"></div>
    <div class="resize-handle resize-handle-e" data-direction="e"></div>
    <div class="resize-handle resize-handle-sw" data-direction="sw"></div>
    <div class="resize-handle resize-handle-s" data-direction="s"></div>
    <div class="resize-handle resize-handle-se" data-direction="se"></div>
  `;
  const iframe = window.querySelector(`#appIframe-${windowId}`);
  iframe.src = homeUrl;
  iframe.dataset.homeUrl = homeUrl;
  
  iframe.dataset.history = JSON.stringify([homeUrl]);
      iframe.onload = function() {
        loadingWrapper.classList.add('hidden');
        updateUrlDisplay(windowElement, url);
        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        if (iframeDoc && iframeDoc.body) {
            iframeDoc.body.addEventListener('click', () => {
                bringWindowToFront(windowElement);
            }, true);
        }
        updateHistoryState(iframe);
        updateBackButtonState(windowElement, iframe);
    };

  iframe.addEventListener('load', function() {
      const loadingWrapper = window.querySelector('.loading-wrapper');
      if (loadingWrapper)
          loadingWrapper.classList.add('hidden');
      const urlDisplay = document.getElementById(`urlDisplay-${windowId}`);
      if (urlDisplay) {
          try {
              urlDisplay.textContent = iframe.contentWindow.location.href;
              const currentUrl = iframe.contentWindow.location.href;
              const history = JSON.parse(iframe.dataset.history || '[]');
              if (history[history.length - 1] !== currentUrl) {
                  history.push(currentUrl);
                  iframe.dataset.history = JSON.stringify(history);
              }
              updateBackButtonState(windowId);
          } catch (e) {
              urlDisplay.textContent = homeUrl;
          }
      }
      iframe.dataset.canGoForward = "false";
  });
  
  const updateUrlDisplay = () => {
    const urlDisplay = document.getElementById(`urlDisplay-${windowId}`);
    if (urlDisplay) {
      try {
        urlDisplay.textContent = iframe.contentWindow.location.href;
      } catch (e) {}
    }
  };
  
  iframe.addEventListener('load', updateUrlDisplay);
  setInterval(updateUrlDisplay, 100);
  
  iframe.addEventListener('mousedown', function(e) {
    bringWindowToFront(window);
  });
  
  iframe.addEventListener('beforeunload', function(e) {});
  
  if (iframe.contentWindow) {
    const originalPushState = iframe.contentWindow.history.pushState;
    iframe.contentWindow.history.pushState = function(state, title, url) {
      originalPushState.apply(this, arguments);
      iframe.dataset.canGoForward = "false";
    };
  }
  
  document.body.appendChild(window);
  return window;
}

function openNewApp() {
  const windowId = generateWindowId();
  const newWindow = createNewWindow(windowId, '测试应用', 'annex/index.html');
  
  newWindow.style.opacity = '0';
  newWindow.style.transform = 'scale(0.95)';
  
  addAppToTaskbar(windowId, '测试应用');
  
  setTimeout(() => {
    newWindow.style.transition = 'opacity 0.2s ease, transform 0.2s ease';
    newWindow.style.opacity = '1';
    newWindow.style.transform = 'scale(1)';
  }, 10);
  
  bringWindowToFront(newWindow);
}

function removeAppFromTaskbar(windowId) {
  const taskbarApp = document.querySelector(`.taskbar-app[data-window="${windowId}"]`);
  if (taskbarApp) {
    taskbarApp.style.transition = 'all 0.2s ease';
    taskbarApp.style.opacity = '0';
    taskbarApp.style.transform = 'scale(0.8)';
    taskbarApp.style.margin = '0 2px';

    setTimeout(() => {
      taskbarApp.remove();
    }, 200);
  }
}

function addAppToTaskbar(windowId, appName) {
  const taskbarApps = document.getElementById('taskbarApps');

  const existingApp = taskbarApps.querySelector(`[data-window="${windowId}"]`);
  if (existingApp) {
    return;
  }

  // 从desktop.json动态读取应用图标
  let iconPath = 'default-icon.png'; // 默认图标
  
  // 特殊处理测试应用
  if (appName === '测试应用') {
    // 创建任务栏图标元素
    const taskbarApp = document.createElement('div');
    taskbarApp.className = 'taskbar-app';
    taskbarApp.dataset.window = windowId;
    taskbarApp.innerHTML = `
      <img src="${iconPath}" width="24" height="24" style="object-fit: contain;" />
    `;
    
    // 添加点击事件
    taskbarApp.addEventListener('click', () => {
      const window = document.getElementById(windowId);
      const isHidden = window.style.display === 'none';
      const isMinimized = window.classList.contains('minimized');
      const currentZIndex = parseInt(window.style.zIndex);
      let maxZIndex = 0;

      document.querySelectorAll('.window').forEach(win => {
        const winZIndex = parseInt(win.style.zIndex);
        if (winZIndex > maxZIndex) {
          maxZIndex = winZIndex;
        }
      });

      if (isHidden) {
        openTestApp();
      } else if (isMinimized) {
        restoreWindow(windowId);
      } else if (currentZIndex === maxZIndex) {
        minimizeWindow(windowId);
      } else {
        bringWindowToFront(window);
      }
    });
    
    taskbarApps.appendChild(taskbarApp);
      
      // 添加过渡效果
      setTimeout(() => {
        taskbarApp.style.transition = 'all 0.2s ease';
        taskbarApp.style.opacity = '1';
        taskbarApp.style.transform = 'scale(1)';
      }, 10);
      return;
  }
  
  // 其他应用从desktop.json动态加载图标
  fetch('desktop.json')
    .then(response => {
      if (response.ok) {
        return response.json();
      }
      throw new Error('Network response was not ok');
    })
    .then(desktopApps => {
      // 根据应用名称查找对应的图标
      const app = desktopApps.find(item => item.name === appName);
      if (app && app.icon) {
        iconPath = app.icon;
      }
      
      // 创建任务栏图标元素
      const taskbarApp = document.createElement('div');
      taskbarApp.className = 'taskbar-app';
      taskbarApp.dataset.window = windowId;
      taskbarApp.innerHTML = `
        <img src="${iconPath}" width="24" height="24" style="object-fit: contain;" />
      `;
      
      // 添加点击事件
      taskbarApp.addEventListener('click', () => {
        const window = document.getElementById(windowId);
        const isHidden = window.style.display === 'none';
        const isMinimized = window.classList.contains('minimized');
        const currentZIndex = parseInt(window.style.zIndex);
        let maxZIndex = 0;

        document.querySelectorAll('.window').forEach(win => {
          const winZIndex = parseInt(win.style.zIndex);
          if (winZIndex > maxZIndex) {
            maxZIndex = winZIndex;
          }
        });

        if (isHidden) {
          openTestApp();
        } else if (isMinimized) {
          restoreWindow(windowId);
        } else if (currentZIndex === maxZIndex) {
          minimizeWindow(windowId);
        } else {
          bringWindowToFront(window);
        }
      });
      
      taskbarApps.appendChild(taskbarApp);
      
      // 添加过渡效果
      setTimeout(() => {
        taskbarApp.style.transition = 'all 0.2s ease';
        taskbarApp.style.opacity = '1';
        taskbarApp.style.transform = 'scale(1)';
      }, 10);
    })
    .catch(error => {
      console.error('加载desktop.json失败:', error);
      // 加载失败时使用默认图标
      const taskbarApp = document.createElement('div');
      taskbarApp.className = 'taskbar-app';
      taskbarApp.dataset.window = windowId;
      taskbarApp.innerHTML = `
        <img src="${iconPath}" width="24" height="24" style="object-fit: contain;" />
      `;
      
      // 添加点击事件
      taskbarApp.addEventListener('click', () => {
        const window = document.getElementById(windowId);
        const isHidden = window.style.display === 'none';
        const isMinimized = window.classList.contains('minimized');
        const currentZIndex = parseInt(window.style.zIndex);
        let maxZIndex = 0;

        document.querySelectorAll('.window').forEach(win => {
          const winZIndex = parseInt(win.style.zIndex);
          if (winZIndex > maxZIndex) {
            maxZIndex = winZIndex;
          }
        });

        if (isHidden) {
          openTestApp();
        } else if (isMinimized) {
          restoreWindow(windowId);
        } else if (currentZIndex === maxZIndex) {
          minimizeWindow(windowId);
        } else {
          bringWindowToFront(window);
        }
      });
      
      taskbarApps.appendChild(taskbarApp);
      
      // 添加过渡效果
      setTimeout(() => {
        taskbarApp.style.transition = 'all 0.2s ease';
        taskbarApp.style.opacity = '1';
        taskbarApp.style.transform = 'scale(1)';
      }, 10);
    });
  

}

function minimizeWindow(windowId) {
    const win = document.getElementById(windowId);
    if (!win) return;
    const isMaximized = win.classList.contains('maximized');

    win.dataset.lastLeft = win.style.left;
    win.dataset.lastTop = win.style.top;
    win.dataset.lastWidth = win.style.width;
    win.dataset.lastHeight = win.style.height;

    win.offsetHeight;
  
    win.style.transition = 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)';
    win.style.transform = 'translateY(100vh)';
    win.style.opacity = '0';
    win.style.pointerEvents = 'none';
  
    setTimeout(() => {
        win.classList.add('minimized');
        win.style.transform = '';
        win.style.opacity = '';
        win.style.pointerEvents = '';
        win.style.transition = '';
        
        if (isMaximized) {
            win.classList.add('maximized');
        }
    }, 200);
  
    const taskbarApp = document.querySelector(`.taskbar-app[data-window="${windowId}"]`);
    if (taskbarApp) {
        taskbarApp.classList.remove('active');
    }
}


function goBack(windowId) {
    const window = document.getElementById(windowId);
    if (!window) return;
    const iframe = window.querySelector(`#appIframe-${windowId}`);
    if (!iframe) return;

    const history = JSON.parse(iframe.dataset.history || '[]');
    if (history.length <= 1) return;
    history.pop();
    const prevUrl = history[history.length - 1];
    iframe.dataset.history = JSON.stringify(history);

    const loadingWrapper = window.querySelector('.loading-wrapper');
    if (loadingWrapper) loadingWrapper.classList.remove('hidden');

    iframe.src = prevUrl;
    iframe.onload = function() {
        if (loadingWrapper) loadingWrapper.classList.add('hidden');
        updateBackButtonState(windowId);
    };
}

function goHome(windowId) {
  const window = document.getElementById(windowId);
  if (!window) return;
  const iframe = window.querySelector(`#appIframe-${windowId}`);
  if (iframe) {
    iframe.src = iframe.dataset.homeUrl || 'annex/index.html';
    const loadingWrapper = window.querySelector('.loading-wrapper');
    if (loadingWrapper) loadingWrapper.classList.remove('hidden');
    iframe.onload = function() {
      if (loadingWrapper) loadingWrapper.classList.add('hidden');
    };
  }
}

function refreshPage(windowId) {
    const window = document.getElementById(windowId);
    if (!window)
        return;
    const iframe = window.querySelector(`#appIframe-${windowId}`);
    if (iframe)
        {
        const loadingWrapper = window.querySelector('.loading-wrapper');
        if (loadingWrapper)
            loadingWrapper.classList.remove('hidden');
        iframe.src = iframe.src;
        iframe.onload = function() {
            if (
                loadingWrapper)
                loadingWrapper.classList.add('hidden');
        };
    }
}

function updateBackButtonState(windowId) {
    const window = document.getElementById(windowId);
    if (!window) return;
    const iframe = window.querySelector(`#appIframe-${windowId}`);
    if (!iframe) return;

    const backButton = window.querySelector('.window-btn.back');
    if (!backButton) return;

    const history = JSON.parse(iframe.dataset.history || '[]');
    const canGoBack = history.length > 1;

    backButton.disabled = !canGoBack;
    backButton.style.opacity = canGoBack ? '1' : '0.5';
    backButton.style.pointerEvents = canGoBack ? 'auto' : 'none';
}

function updateUrlDisplay() {
    const currentUrl = getCurrentUrl();
    const urlDisplay = document.getElementById('url-display');
    urlDisplay.textContent = currentUrl;
    urlDisplay.title = currentUrl;
}

function restoreWindow(windowId) {
  const win = document.getElementById(windowId);
  const taskbarApp = document.querySelector(`.taskbar-app[data-window="${windowId}"]`);
  
  if (!taskbarApp) {
    win.classList.remove('minimized');
    win.style.display = 'block';
    return;
  }
  
  win.style.transition = 'none';
  win.classList.remove('minimized');
  win.style.display = 'block';
  win.style.opacity = '0';
  win.style.transform = 'translateY(100vh)';
  win.style.pointerEvents = 'none';
  
  win.style.left = win.dataset.lastLeft || '100px';
  win.style.top = win.dataset.lastTop || '100px';
  win.style.width = win.dataset.lastWidth || '800px';
  win.style.height = win.dataset.lastHeight || '600px';
  
  win.offsetHeight;
  
  win.style.transition = 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)';
  win.style.transform = 'translateY(0)';
  win.style.opacity = '1';
  
  setTimeout(() => {
    win.style.pointerEvents = '';
    win.style.transition = '';
  }, 200);
  
  bringWindowToFront(win);
}

function maximizeWindow(windowId) {
  const win = document.getElementById(windowId);
  
  if (win.classList.contains('maximized')) {
    const lastLeft = win.dataset.lastLeft || '100px';
    const lastTop = win.dataset.lastTop || '100px';
    const lastWidth = win.dataset.lastWidth || '800px';
    const lastHeight = win.dataset.lastHeight || '600px';
    
    // 1. 先移除maximized类
    win.classList.remove('maximized');
    
    // 2. 强制重排
    win.offsetHeight;
    
    // 3. 设置过渡动画
    win.style.transition = 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)';
    win.style.width = lastWidth;
    win.style.height = lastHeight;
    win.style.left = lastLeft;
    win.style.top = lastTop;
    
    // 4. 延迟时间略长于动画时长
    setTimeout(() => {
      win.style.transition = '';
    }, 220);
  } else {
    win.dataset.lastLeft = win.style.left;
    win.dataset.lastTop = win.style.top;
    win.dataset.lastWidth = win.style.width;
    win.dataset.lastHeight = win.style.height;
    
    win.style.transition = 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)';
    win.style.width = 'calc(100% - 40px)';
    win.style.height = 'calc(100% - 40px)';
    win.style.left = '20px';
    win.style.top = '20px';
    
    setTimeout(() => {
      win.classList.add('maximized');
      win.style.transition = '';
    }, 220);
  }
}

function closeWindow(windowId) {
  const win = document.getElementById(windowId);
  if (!win) return;

  win.style.transition = 'all 0.2s ease';
  win.style.opacity = '0';
  win.style.transform = 'scale(0.95)';

  setTimeout(() => {
    win.remove();
    removeAppFromTaskbar(windowId);
  }, 200);
}

function bringWindowToFront(window) {
  currentWindowZIndex++;
  window.style.zIndex = currentWindowZIndex;
  
  const windowId = window.id;
  document.querySelectorAll('.taskbar-app').forEach(app => {
    if (app.dataset.window === windowId) {
      app.classList.add('active');
    } else {
      app.classList.remove('active');
    }
  });
}

function initWindowDragging() {
  document.addEventListener('mousedown', handleDragStart);
  document.addEventListener('touchstart', handleDragStart, { passive: false });

  document.addEventListener('mousemove', handleDragMove);
  document.addEventListener('touchmove', handleDragMove, { passive: false });

  document.addEventListener('mouseup', handleDragEnd);
  document.addEventListener('touchend', handleDragEnd);
  document.addEventListener('touchcancel', handleDragEnd);

  document.addEventListener('mouseleave', handleDragEnd);

  function handleDragStart(e) {
    const window = e.target.closest('.window');
    if (!window) return;

    const header = e.target.closest('.window-header');
    if (e.target.closest('.window-btn')) {
      return;
    }

    bringWindowToFront(window);

    if (!header) return;

    if (window.classList.contains('maximized')) {
      return;
    }

    e.preventDefault(); 

    const rect = window.getBoundingClientRect();
    const { clientX, clientY } = getTouchOrMousePosition(e);
    dragOffsetX = clientX - rect.left;
    dragOffsetY = clientY - rect.top;

    bringWindowToFront(window);

    isDragging = true;
    currentWindow = window;

    window.classList.add('dragging');

    window.style.transition = 'none';
  }

  function handleDragMove(e) {
    if (!isDragging || !currentWindow) return;

    e.preventDefault(); 

    const { clientX, clientY } = getTouchOrMousePosition(e);
    let newX = clientX - dragOffsetX;
    let newY = clientY - dragOffsetY;

    newX = Math.max(0, Math.min(newX, window.innerWidth - currentWindow.offsetWidth));
    newY = Math.max(0, Math.min(newY, window.innerHeight - currentWindow.offsetHeight - 48)); 

    currentWindow.style.left = `${newX}px`;
    currentWindow.style.top = `${newY}px`;
  }

  function handleDragEnd() {
    if (currentWindow) {
      currentWindow.classList.remove('dragging');
      currentWindow.style.transition = '';
    }
    isDragging = false;
    currentWindow = null;
  }

  function getTouchOrMousePosition(e) {
    if (e.touches) {
      return {
        clientX: e.touches[0].clientX,
        clientY: e.touches[0].clientY
      };
    }
    return {
      clientX: e.clientX,
      clientY: e.clientY
    };
  }
}

function initWindowResizing() {
  document.addEventListener('mousedown', handleResizeStart);
  document.addEventListener('touchstart', handleResizeStart, { passive: false });

  function handleResizeStart(e) {
    const handle = e.target.closest('.resize-handle');
    if (!handle) return;
  
    const win = handle.closest('.window');
    if (!win || win.classList.contains('maximized')) return;
  
    e.preventDefault(); 
  
    const rect = win.getBoundingClientRect();
    const { clientX: startX, clientY: startY } = getTouchOrMousePosition(e);
  
    const startLeft = rect.left;
    const startTop = rect.top;
    const startRight = rect.right;
    const startBottom = rect.bottom;
  
    const minWidth = 300;
    const minHeight = 200;
  
    win.style.transition = 'none';
    document.body.style.cursor = getComputedStyle(handle).cursor;
  
    function moveHandler(e) {
      e.preventDefault(); 
  
      const { clientX: mouseX, clientY: mouseY } = getTouchOrMousePosition(e);
  
      const deltaX = mouseX - startX;
      const deltaY = mouseY - startY;
  
      switch(handle.dataset.direction) {
        case 'nw': 
          win.style.left = Math.min(startRight - minWidth, startLeft + deltaX) + 'px';
          win.style.top = Math.min(startBottom - minHeight, startTop + deltaY) + 'px';
          win.style.width = Math.max(minWidth, startRight - (startLeft + deltaX)) + 'px';
          win.style.height = Math.max(minHeight, startBottom - (startTop + deltaY)) + 'px';
          break;
        case 'n': 
          win.style.top = Math.min(startBottom - minHeight, startTop + deltaY) + 'px';
          win.style.height = Math.max(minHeight, startBottom - (startTop + deltaY)) + 'px';
          break;
        case 'ne': 
          win.style.top = Math.min(startBottom - minHeight, startTop + deltaY) + 'px';
          win.style.width = Math.max(minWidth, (startRight - startLeft) + deltaX) + 'px';
          win.style.height = Math.max(minHeight, startBottom - (startTop + deltaY)) + 'px';
          break;
        case 'e': 
          win.style.width = Math.max(minWidth, (startRight - startLeft) + deltaX) + 'px';
          break;
        case 'se': 
          win.style.width = Math.max(minWidth, (startRight - startLeft) + deltaX) + 'px';
          win.style.height = Math.max(minHeight, (startBottom - startTop) + deltaY) + 'px';
          break;
        case 's': 
          win.style.height = Math.max(minHeight, (startBottom - startTop) + deltaY) + 'px';
          break;
        case 'sw': 
          win.style.left = Math.min(startRight - minWidth, startLeft + deltaX) + 'px';
          win.style.width = Math.max(minWidth, startRight - (startLeft + deltaX)) + 'px';
          win.style.height = Math.max(minHeight, (startBottom - startTop) + deltaY) + 'px';
          break;
        case 'w': 
          win.style.left = Math.min(startRight - minWidth, startLeft + deltaX) + 'px';
          win.style.width = Math.max(minWidth, startRight - (startLeft + deltaX)) + 'px';
          break;
      }
    }
  
    function upHandler() {
      win.dataset.lastLeft = win.style.left;
      win.dataset.lastTop = win.style.top;
      win.dataset.lastWidth = win.style.width;
      win.dataset.lastHeight = win.style.height;
  
      document.removeEventListener('mousemove', moveHandler);
      document.removeEventListener('touchmove', moveHandler);
      document.removeEventListener('mouseup', upHandler);
      document.removeEventListener('touchend', upHandler);
      document.removeEventListener('touchcancel', upHandler);
      document.body.style.cursor = '';
      win.style.transition = '';
    }
  
    document.addEventListener('mousemove', moveHandler);
    document.addEventListener('touchmove', moveHandler, { passive: false });
    document.addEventListener('mouseup', upHandler);
    document.addEventListener('touchend', upHandler);
    document.addEventListener('touchcancel', upHandler);
  }
}

function initButtonTouchSupport() {
  document.addEventListener('touchstart', (e) => {
    const button = e.target.closest('.window-btn');
    if (button) {
      e.preventDefault(); 
      button.click(); 
    }
  }, { passive: false });
}

function init() {
  setWallpaper();
  updateDateTime();
  initWindowDragging();
  initWindowResizing();
  initButtonTouchSupport(); 
  initStartMenu();
  setInterval(updateDateTime, 60000); 
}

window.addEventListener('load', init);

function initWindowResizing() {
  document.addEventListener('mousedown', function(e) {
    const handle = e.target.closest('.resize-handle');
    if (!handle) return;
    
    const win = handle.closest('.window');
    if (!win || win.classList.contains('maximized')) return;
    
    e.preventDefault();
    e.stopPropagation();
    
    const rect = win.getBoundingClientRect();
    const startX = e.clientX;
    const startY = e.clientY;
    
    const startLeft = rect.left;
    const startTop = rect.top;
    const startRight = rect.right;
    const startBottom = rect.bottom;
    
    const minWidth = 300;
    const minHeight = 200;
    
    win.style.transition = 'none';
    document.body.style.cursor = getComputedStyle(handle).cursor;
    
    function moveHandler(e) {
      const mouseX = e.clientX;
      const mouseY = e.clientY;
      
      const deltaX = mouseX - startX;
      const deltaY = mouseY - startY;
      
      switch(handle.dataset.direction) {
        case 'nw': 
          win.style.left = Math.min(startRight - minWidth, startLeft + deltaX) + 'px';
          win.style.top = Math.min(startBottom - minHeight, startTop + deltaY) + 'px';
          win.style.width = Math.max(minWidth, startRight - (startLeft + deltaX)) + 'px';
          win.style.height = Math.max(minHeight, startBottom - (startTop + deltaY)) + 'px';
          break;
        case 'n': 
          win.style.top = Math.min(startBottom - minHeight, startTop + deltaY) + 'px';
          win.style.height = Math.max(minHeight, startBottom - (startTop + deltaY)) + 'px';
          break;
        case 'ne': 
          win.style.top = Math.min(startBottom - minHeight, startTop + deltaY) + 'px';
          win.style.width = Math.max(minWidth, (startRight - startLeft) + deltaX) + 'px';
          win.style.height = Math.max(minHeight, startBottom - (startTop + deltaY)) + 'px';
          break;
        case 'e': 
          win.style.width = Math.max(minWidth, (startRight - startLeft) + deltaX) + 'px';
          break;
        case 'se': 
          win.style.width = Math.max(minWidth, (startRight - startLeft) + deltaX) + 'px';
          win.style.height = Math.max(minHeight, (startBottom - startTop) + deltaY) + 'px';
          break;
        case 's': 
          win.style.height = Math.max(minHeight, (startBottom - startTop) + deltaY) + 'px';
          break;
        case 'sw': 
          win.style.left = Math.min(startRight - minWidth, startLeft + deltaX) + 'px';
          win.style.width = Math.max(minWidth, startRight - (startLeft + deltaX)) + 'px';
          win.style.height = Math.max(minHeight, (startBottom - startTop) + deltaY) + 'px';
          break;
        case 'w': 
          win.style.left = Math.min(startRight - minWidth, startLeft + deltaX) + 'px';
          win.style.width = Math.max(minWidth, startRight - (startLeft + deltaX)) + 'px';
          break;
      }
    }
    
    function upHandler() {
      win.dataset.lastLeft = win.style.left;
      win.dataset.lastTop = win.style.top;
      win.dataset.lastWidth = win.style.width;
      win.dataset.lastHeight = win.style.height;
      
      document.removeEventListener('mousemove', moveHandler);
      document.removeEventListener('mouseup', upHandler);
      document.body.style.cursor = '';
      win.style.transition = '';
    }
    
    document.addEventListener('mousemove', moveHandler);
    document.addEventListener('mouseup', upHandler);
  });
}

function showPowerMenu() {
  const powerMenuPopup = document.getElementById('powerMenuPopup');
  powerMenuPopup.classList.add('show');
  blurOverlay.classList.add('active');
  powerMenuOpen = true;
}

function hidePowerMenu() {
  const powerMenuPopup = document.getElementById('powerMenuPopup');
  powerMenuPopup.classList.remove('show');
  powerMenuOpen = false;
  
  if (!document.querySelector('.calendar-popup.show') && 
      !document.querySelector('.power-confirm-popup.show')) {
    blurOverlay.classList.remove('active');
  }
}

function restartSystem() {
  hidePowerMenu();
  const powerConfirmPopup = document.getElementById('powerConfirmPopup');
  const confirmMessage = document.getElementById('confirmMessage');
  
  confirmMessage.textContent = '确定要重启此电脑吗？';
  powerConfirmPopup.classList.add('show');
  blurOverlay.classList.add('active');
}

function shutdownSystem() {
  hidePowerMenu();
  const powerConfirmPopup = document.getElementById('powerConfirmPopup');
  const confirmMessage = document.getElementById('confirmMessage');
  
  confirmMessage.textContent = '确定要关闭此电脑吗？';
  powerConfirmPopup.classList.add('show');
  blurOverlay.classList.add('active');
}

function cancelPowerMenu() {
  hidePowerMenu();
}

function togglePowerMenu() {
  const powerMenu = document.getElementById('powerMenuPopup');
  powerMenuOpen = !powerMenuOpen;
  
  if (powerMenuOpen) {
    powerMenu.classList.add('show');
    blurOverlay.classList.add('active');
  } else {
    powerMenu.classList.remove('show');
    if (!calendarOpen) {
      blurOverlay.classList.remove('active');
    }
  }
}

function confirmAction(confirm) {
  const powerConfirmPopup = document.getElementById('powerConfirmPopup');
  powerConfirmPopup.classList.remove('show');
  
  if (confirm) {
    const message = document.getElementById('confirmMessage').textContent;
    
    if (message.includes('重启')) {
      location.reload();
    } else if (message.includes('关闭')) {
      window.close();
    }
  }
  
  if (!document.querySelector('.calendar-popup.show') && 
      !document.querySelector('.power-menu-popup.show')) {
    blurOverlay.classList.remove('active');
  }
}

document.addEventListener('DOMContentLoaded', () => {
  setWallpaper();
  
  updateDateTime();
  setInterval(updateDateTime, 1000);
  
  initWindowDragging();
  
  const datetime = document.getElementById('datetime');
  datetime.addEventListener('click', () => {
    if (calendarOpen) {
      hideCalendarPopup();
    } else {
      showCalendarPopup();
    }
  });
  
  const startButton = document.getElementById('startButton');
  startButton.addEventListener('click', () => {
    if (powerMenuOpen) {
      hidePowerMenu();
    } else {
      showPowerMenu();
    }
  });
  
  document.addEventListener('click', (e) => {
    const powerMenuPopup = document.getElementById('powerMenuPopup');
    const calendarPopup = document.getElementById('calendarPopup');
    
    if (!startButton.contains(e.target) && !powerMenuPopup.contains(e.target)) {
      hidePowerMenu();
    }
    
    if (!datetime.contains(e.target) && !calendarPopup.contains(e.target)) {
      hideCalendarPopup();
    }
  });
});

function openApp(url, appName) {
  const windowId = generateWindowId();
  const newWindow = createNewWindow(windowId, appName, url);
  const iframe = document.getElementById(`appIframe-${windowId}`);
  
  if (iframe) {
    iframe.src = url;
  }
  
  newWindow.style.opacity = '0';
  
  window.addEventListener('message', (event) => {
    if (event.data.type === 'switchWindow') {
      const windowId = event.data.windowId;
      const win = document.getElementById(windowId);
      if (win) {
        bringWindowToFront(win);
      }
    }
  });
  newWindow.style.transform = 'scale(0.95)';
  
  addAppToTaskbar(windowId, appName); 
  
  setTimeout(() => {
    newWindow.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
    newWindow.style.opacity = '1';
    newWindow.style.transform = 'scale(1)';
  }, 10);
  
  bringWindowToFront(newWindow);
}

function initDesktopIcons() {
  fetch('desktop.json')
    .then(response => {
      if (!response.ok) {
        throw new Error('网络响应不正常');
      }
      return response.json();
    })
    .then(apps => {
      const desktopIcons = document.querySelector('.desktop-icons');
      desktopIcons.innerHTML = ''; 
      
      apps.forEach(app => {
      const icon = document.createElement('div');
      icon.className = 'desktop-icon';
      icon.onclick = () => openApp(app.url, app.name); 

      icon.innerHTML = `
        <div class="icon-image">
          <img src="${app.icon}" alt="${app.name}" width="48" height="48" onerror="this.src='default-icon.png'">
        </div>
        <div class="icon-text">${app.name}</div>
      `;

      desktopIcons.appendChild(icon);
    });
    })
    .catch(error => console.error('加载应用配置失败:', error));
}

window.addEventListener('load', () => {
  setWallpaper();
  updateDateTime();
  setInterval(updateDateTime, 60000);
  initWindowDragging();
  initWindowResizing(); 
  initDesktopIcons();
});